const Koa = require('koa'),
	app = new Koa(),
	cors = require('koa-cors'),
	_static = require('koa-static'),
	views = require('koa-views'),
	json = require('koa-json'),
	onerror = require('koa-onerror'),
	bodyparser = require('koa-bodyparser'),
	logger = require('koa-logger');

const test_middleware = require('./middleware/test_middleware');
const test_middleware2 = require('./middleware/test_middleware2');

// error handler 错误的异常处理
onerror(app);

const router = require('./router.js'); //路由

// 测试自定义的中间件
app.use(test_middleware("Middleware"));
app.use(test_middleware2("Middleware2"));

// middlewares
app.use(cors()); //处理跨域的中间件

app.use(bodyparser({
	enableTypes: ['json', 'form', 'text']
}));
app.use(json());
app.use(logger());

// 设置静态资源目录 css,js,images
app.use(_static(__dirname + '/assets'));

// 参考简书：https://www.jianshu.com/p/31bdea860a4c?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
app.use(views(__dirname + '/views', {
	map: {html: 'ejs'}
	//模板文件的后缀名为html
}));

// logger
app.use(async (ctx, next) => {
	const start = new Date();
	await next();
	const ms = new Date() - start;
	console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(router.routes());
app.use(router.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
	console.error('server error', err, ctx)
});

module.exports = app;